package com.huatai.datacenter.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.api.R;
import com.huatai.common.httputil.HttpRequest;
import com.huatai.datacenter.entity.ApiEntity;
import com.huatai.datacenter.entity.postdata.HttpRequestEntity;
import com.huatai.datacenter.mapper.ApiMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Lion
 * @date 2023/4/18  9:09
 */
@Service
public class ApiService extends BaseService<ApiMapper, ApiEntity> {

	@Autowired
	private DataModelApplyService dataModelApplyService;

	@Autowired
	private ApiMapper apiMapper;

	public ApiEntity getConfig(String path) {
		return apiMapper.selectByPathOnline(path);
	}

	/**
	 * @author Lion
	 * @description
	 * @param request
	 * @param config
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 */
	public Map<String, Object> getSqlParam(HttpServletRequest request, ApiEntity config) {

		Map<String, Object> map = new HashMap<>();

		//从浏览器中获取参数，将参数值加载到SQL语句中
		if (StringUtils.isNotBlank(config.getParams())){
			JSONArray requestParams = JSON.parseArray(config.getParams());
			for (int i = 0; i < requestParams.size(); i++) {
				JSONObject jo = requestParams.getJSONObject(i);
				String name = jo.getString("name");
				String type = jo.getString("type");

				//数组类型参数
				if (type.startsWith("Array")) {
					String[] values = request.getParameterValues(name);
					if (values != null) {
						List<String> list = Arrays.asList(values);
						if (values.length > 0) {
							switch (type) {
								case "Array<double>":
									List<Double> collect = list.stream().map(value -> Double.valueOf(value)).collect(Collectors.toList());
									map.put(name, collect);
									break;
								case "Array<bigint>":
									List<Long> longs = list.stream().map(value -> Long.valueOf(value)).collect(Collectors.toList());
									map.put(name, longs);
									break;
								case "Array<string>":
								case "Array<date>":
									map.put(name, list);
									break;
							}
						} else {
							map.put(name, list);
						}
					} else {
						map.put(name, null);
					}
				} else {

					String value = request.getParameter(name);
					if (StringUtils.isNotBlank(value)) {

						switch (type) {
							case "double":
								Double v = Double.valueOf(value);
								map.put(name, v);
								break;
							case "bigint":
								Long longV = Long.valueOf(value);
								map.put(name, longV);
								break;
							case "string":
							case "date":
								map.put(name, value);
								break;
						}
					} else {
						map.put(name, value);
					}
				}
			}
		}

		return map;
	}

	/**
	 * @author Lion
	 * @description 根据url和body参数发送请求
	 * @param @param url
	 * @param body
	 * @return java.lang.String
	 */
	public String sendData(String method,String url,String body){

		String resObj = "";
		if ("POST".equals(method)){
			resObj = HttpRequest
				.post(url)
				.bodyString(body)
				.execute()
				.asString();
		}else {
			resObj = HttpRequest
				.get(url)
				.execute()
				.asString();
		}

		return resObj;
	}

	/**
	 * @author Lion
	 * @description 添加服务应用记录
	 * @param entity
	 * @return void
	 */
	public void saveAPIApply(ApiEntity entity){
		if (StrUtil.isEmpty(entity.getModelId())){
			dataModelApplyService.saveDataModelApplyInstance(Long.valueOf(entity.getModelId()),entity.getModelName(),entity.getId(),entity.getApiName(),"服务类数据模型");
		}
	}

	public List<ApiEntity> getConfigList(String processedUri) {
		QueryWrapper<ApiEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("path", processedUri);
		return apiMapper.selectList(queryWrapper);
	}
}
